#include "clientFunc.h"

// 传入cmd_t，解析并执行相应的指令函数,传入cwd_t为指令函数传参
int cmdClientHandler(int sockfd, cmd_t *pcmd) {
    switch(pcmd->cmdToken[0]) {
    case'c': cdProc(sockfd, &cwd, pcmd); break; 
    case'l': 
             switch(pcmd->cmdToken[1]) {
             case's': lsProc(sockfd, &cwd, pcmd); break;
             case'o': 
                      switch(pcmd->cmdToken[3]) {
                      case'i': userLoginProc(sockfd, pcmd);break;
                      case'o': userLogoutProc();break;
                      }
                      break;
             }
             break;
    case'p': 
             switch(pcmd->cmdToken[1]) {
             case'u': makeTransRequest(pcmd); break;
             case'w': pwdProc(&cwd); break;
             }
             break;
    case'u': 
             switch(pcmd->cmdToken[4]){
             case'a':userAddProc(sockfd, pcmd);break;
             case'd':userDelProc(sockfd, pcmd);break;
             }
             break;
    case'g': makeTransRequest(pcmd); break;
    case'm': mkdirProc(sockfd, &cwd, pcmd); break;
    case'r': rmProc(sockfd, &cwd, pcmd); break;
    }
    return 0;
}


// pwd指令(遍历栈),pwdstr用于存储遍历后的结果
int pwdProc(const cwd_t* pcwd) {
    char pwdstr[PATH_MAX] = {0};
    getPath(pcwd, pwdstr);
    printf("%s\n", pwdstr);
    return 0;
}

// 将整个目录流中的内容发送给客户端
static int readDir(int sockfd, train_t* train) {
    while(1) {
        memset(train, 0, sizeof(train_t));
        recvn(sockfd, &train->length, sizeof(int));
        if(train->length == 0) {
            break;
        }
        recvn(sockfd, train->data, train->length);
        printf("%s  ", train->data);
    }
    return 0;
}

// ls指令,cwd_t获取cwd,cmd_t获取指令及参数
int lsProc(int sockfd, cwd_t* pcwd, cmd_t* pcmd) {
    char mergePath[1024] = {0};
    if(pcmd->argc == 0) {
        getPath(pcwd, mergePath);
        memset(pcmd->argv1, 0, sizeof(pcmd->argv1));
        strcpy(pcmd->argv1, pcwd->cwdStr);
    }
    else if(pcmd->argc == 1) {
        parsePath(pcwd, pcmd->argv1, mergePath);
        memset(pcmd->argv1, 0, sizeof(pcmd->argv1));
        strcpy(pcmd->argv1, mergePath);
    }

    send(sockfd, pcmd, sizeof(cmd_t), MSG_NOSIGNAL);
    train_t train;
    if(recvMsg(sockfd, &train)) {
        readDir(sockfd, &train);
    }
    printf("\n");
    return 0;
}

// cd指令,修改cwd栈,cmd_t获取指令及参数
int cdProc(int sockfd, cwd_t* pcwd, cmd_t* pcmd) {
    if(pcmd->argc == 0) {
        memset(pcwd->cwdStr, 0, sizeof(pcwd->cwdStr));
        strcat(pcwd->cwdStr, "/");
        return 0;
    }
    else {
        char mergePath[1024] = {0};
        parsePath(pcwd, pcmd->argv1, mergePath);
        memset(pcmd->argv1, 0, sizeof(pcmd->argv1));
        strcpy(pcmd->argv1, mergePath);
        send(sockfd, pcmd, sizeof(cmd_t), MSG_NOSIGNAL);
        train_t train;
        if(recvMsg(sockfd, &train)) {
            strcpy(pcwd->cwdStr, mergePath);
        }
    }

    return 0;
}    
